package com.hongpu.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hongpu.domain.CoolTowerEmployeeSalaryProjectRelationship;
import com.hongpu.dto.CoolTowerProjectAttendanceDto;
import com.hongpu.dto.EmployeeMonthlyExpensesDto;
import com.hongpu.service.CoolTowerEmployeeSalaryProjectRelationshipService;
import com.hongpu.service.CoolTowerProjectAttendanceService;
import com.hongpu.service.CoolTowerProjectService;
import com.hongpu.service.EmployeeMonthlyExpensesService;
import com.hongpu.utils.OaDateUtils;
import com.hongpu.utils.ResultDto;
import com.hongpu.vo.EmployeeMonthlyExpensesVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 张玉胜
 * @since 2025年06月11日
 */
@Service
public class EmployeeMonthlyExpensesServiceImpl implements EmployeeMonthlyExpensesService {

    @Autowired
    CoolTowerEmployeeSalaryProjectRelationshipService coolTowerEmployeeSalaryProjectRelationshipService;
    @Autowired
    CoolTowerProjectService coolTowerProjectService;
    @Autowired
    CoolTowerProjectAttendanceService coolTowerProjectAttendanceService;


    @Override
    public ResultDto page(EmployeeMonthlyExpensesDto employeeMonthlyExpensesDto) {
        // 单个人费用总额
        BigDecimal singlePersonalExpensesTotal = BigDecimal.ZERO;
        Map<String,Object> result = new HashMap<>();
        try {
            IPage<EmployeeMonthlyExpensesVo> page = new Page<>(employeeMonthlyExpensesDto.getCurrent(), employeeMonthlyExpensesDto.getSize());
            // 员工ID
            Long coolTowerEmployeeId = employeeMonthlyExpensesDto.getCoolTowerEmployeeId();
            // 开始时间
            String startDate = employeeMonthlyExpensesDto.getStartDate();
            if(StringUtils.isEmpty(startDate)){
                startDate = OaDateUtils.firstDayOfLastMonth();
            }else {
                startDate = OaDateUtils.firstDayOfMonth(startDate);
            }
            // 结束时间
            String endDate = employeeMonthlyExpensesDto.getEndDate();
            if(StringUtils.isEmpty(endDate)){
                endDate = OaDateUtils.lastDayOfLastMonth();
            }else {
                endDate = OaDateUtils.lastDayOfMonth(endDate);
            }

            // 查询当前人员所在的项目
            IPage<CoolTowerEmployeeSalaryProjectRelationship> selectPage = coolTowerEmployeeSalaryProjectRelationshipService.selectPage(page, coolTowerEmployeeId);
            page.setCurrent(selectPage.getCurrent());
            page.setTotal(selectPage.getTotal());
            page.setSize(selectPage.getSize());
            List<EmployeeMonthlyExpensesVo> employeeMonthlyExpensesVoList = new ArrayList<>();
            // 根据所在的项目统计相关费用
            List<CoolTowerEmployeeSalaryProjectRelationship> selectPageRecords = selectPage.getRecords();
            if (CollectionUtils.isNotEmpty(selectPageRecords)) {
                for (CoolTowerEmployeeSalaryProjectRelationship coolTowerEmployeeSalaryProjectRelationship : selectPageRecords) {
                    EmployeeMonthlyExpensesVo employeeMonthlyExpensesVo = new EmployeeMonthlyExpensesVo();
                    employeeMonthlyExpensesVo.setWorkNum(coolTowerEmployeeSalaryProjectRelationship.getWorkNum());
                    employeeMonthlyExpensesVo.setName(coolTowerEmployeeSalaryProjectRelationship.getEmployeeName());
                    // 项目ID
                    Long coolTowerProjectId = coolTowerEmployeeSalaryProjectRelationship.getCoolTowerProjectId();
                    // 项目名称
                    String projectName = selectProjectNameById(coolTowerProjectId);
                    employeeMonthlyExpensesVo.setProjectName(projectName);
                    // 统计汇总员工在一个项目上的:工数,日结总费用,补贴,其他费用,总费用
                    CoolTowerProjectAttendanceDto coolTowerProjectAttendanceDto = selectSum(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
                    if(coolTowerProjectAttendanceDto == null){
                        coolTowerProjectAttendanceDto = new CoolTowerProjectAttendanceDto();
                    }
                    // 安装工日  workingHours
                    BigDecimal workingHours = coolTowerProjectAttendanceDto.getNumberOfJobsSum();
                    employeeMonthlyExpensesVo.setWorkingHours(workingHours);
                    // 基本薪资  salary
                    BigDecimal salary = selectSalarySum(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
                    if(salary != null){
                        singlePersonalExpensesTotal = singlePersonalExpensesTotal.add(salary);
                    }
                    employeeMonthlyExpensesVo.setSalary(salary);
                    // 日结总费用 dailySettlementFeeSum
                    BigDecimal dailySettlementFeeSum = coolTowerProjectAttendanceDto.getDailySettlementFeeSum();
                    employeeMonthlyExpensesVo.setDailySettlementFeeSum(dailySettlementFeeSum);
                    // 补助  subsidy
                    BigDecimal subsidy = coolTowerProjectAttendanceDto.getSubsidySum();
                    employeeMonthlyExpensesVo.setSubsidy(subsidy);
                    // 其他费用
                    BigDecimal otherFee = coolTowerProjectAttendanceDto.getOtherExpensesSum();
                    employeeMonthlyExpensesVo.setOtherFee(otherFee);
                    // 打卡日期
                    String checkDate = selectCheckDate(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
                    employeeMonthlyExpensesVo.setCheckDate(checkDate);
                    // 备注
                    String remark = selectRemark(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
                    employeeMonthlyExpensesVo.setRemark(remark);
                    // 总费用
                    BigDecimal totalFee = coolTowerProjectAttendanceDto.getTotalFeeSum();
                    if(totalFee != null){
                        singlePersonalExpensesTotal = singlePersonalExpensesTotal.add(totalFee);
                    }
                    employeeMonthlyExpensesVo.setTotalFee(totalFee);
                    // 最后放到集合中
                    employeeMonthlyExpensesVoList.add(employeeMonthlyExpensesVo);
                }
                page.setRecords(employeeMonthlyExpensesVoList);
            }
            page.setRecords(employeeMonthlyExpensesVoList);
            result.put("page", page);
            result.put("singlePersonalExpensesTotal", singlePersonalExpensesTotal);
            return ResultDto.ok(result);
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 根据项目ID查询项目名称
     *
     * @param id
     */
    @Override
    public String selectProjectNameById(Long id) {
        return coolTowerProjectService.selectProjectNameById(id);
    }


    /**
     * 打卡日期
     *
     * @param cool_tower_project_id
     * @param cool_tower_employee_id
     */
    @Override
    public String selectCheckDate(Long coolTowerProjectId, Long coolTowerEmployeeId, String startDate, String endDate) {
        String checkDate = "";
        try {
            List<String> selectCheckInDates = coolTowerProjectAttendanceService.selectCheckInDate(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
            if(CollectionUtils.isNotEmpty(selectCheckInDates)){
                StringBuilder  stringBuilder = new StringBuilder();
                for (int i = 0; i < selectCheckInDates.size(); i++) {
                    stringBuilder.append(selectCheckInDates.get(i));
                    if(i != selectCheckInDates.size()-1){
                        stringBuilder.append(",");
                    }
                }
                checkDate = stringBuilder.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return checkDate;
    }

    /**
     * 备注
     *
     * @param cool_tower_project_id
     * @param cool_tower_employee_id
     */
    @Override
    public String selectRemark(Long coolTowerProjectId, Long coolTowerEmployeeId,String startDate,  String endDate) {
        String remark = "";
        try {
            List<String> selectRemarks = coolTowerProjectAttendanceService.selectRemark(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
            if(CollectionUtils.isNotEmpty(selectRemarks)){
                StringBuilder  stringBuilder = new StringBuilder();
                for (int i = 0; i < selectRemarks.size(); i++) {
                    stringBuilder.append(selectRemarks.get(i));
                    if(i != selectRemarks.size()-1){
                        stringBuilder.append(",");
                    }
                }
                remark = stringBuilder.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return remark;
    }


    /**
     * 统计汇总员工在一个项目上的:工数,日结总费用,补贴,其他费用,总费用
     *
     * @param cool_tower_project_id
     * @param cool_tower_employee_id
     */
    @Override
    public CoolTowerProjectAttendanceDto selectSum(Long coolTowerProjectId, Long coolTowerEmployeeId,String startDate,  String endDate) {
        CoolTowerProjectAttendanceDto selectSum = null;
        try {
            selectSum =  coolTowerProjectAttendanceService.selectSum(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return selectSum;
    }


    /**
     * 基本工资合计
     *
     * @param cool_tower_project_id
     * @param cool_tower_employee_id
     */
    @Override
    public BigDecimal selectSalarySum(Long coolTowerProjectId, Long coolTowerEmployeeId, String startDate, String endDate) {
        BigDecimal selectSalarySum = BigDecimal.ZERO;
        try  {
            // 查询基本工资,参数：cool_tower_project_id，cool_tower_employee_id
            BigDecimal salary = coolTowerEmployeeSalaryProjectRelationshipService.selectSalary(coolTowerProjectId, coolTowerEmployeeId);
            if(salary == null){
                salary = BigDecimal.ZERO;
            }
            // 查询 startDate 到 endDate 有几个月
            int monthCount = coolTowerEmployeeSalaryProjectRelationshipService.selectMonth(startDate, endDate);
            // 计算总的工资数
            selectSalarySum = salary.multiply(new BigDecimal(monthCount));
          }catch (Exception e){
            e.printStackTrace();
        }
        return selectSalarySum;
    }
}